import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 17655
 * Date: 2025-08-05
 * Time: 21:58
 */
public class test2 {
    // 归并排序
    public ListNode sortList(ListNode head) {
        if(head==null || head.next==null){
            return head;
        }
        ListNode mid = findMiddle(head);
        ListNode rightHead = mid.next;
        // 断开
        mid.next = null;

        ListNode left = sortList(head);
        ListNode right = sortList(rightHead);

        // 合并两个链表
        return mergeTwoLists(left,right);
    }

    private ListNode findMiddle(ListNode head){
        ListNode slow = head;
        ListNode fast = head.next;
        // fast走两步，slow走一步
        while(fast!=null && fast.next!=null){
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }

    private ListNode mergeTwoLists(ListNode l1,ListNode l2){
        ListNode pre = new ListNode(-1);
        // 进行移动
        ListNode cur = pre;
        while(l1!=null && l2!=null){
            if(l1.val<l2.val){
                cur.next = l1;
                l1 = l1.next;
            }else{
                cur.next = l2;
                l2 = l2.next;
            }
            cur = cur.next;
        }

        // 将剩余的链表补上
        if(l1!=null){
            cur.next = l1;
        }
        if(l2!=null){
            cur.next = l2;
        }

        return pre.next;
    }

    class ListNode{
        int val;
        ListNode next;

        public ListNode(int val){
            this.val = val;
            this.next = next;
        }
    }
}
